package com.ruitu.health_2.ui.mall;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.androidkun.xtablayout.XTabLayout;
import com.ruitu.arad.base.BaseFragment;
import com.ruitu.arad.base.base_list.ListBaseAdapter;
import com.ruitu.arad.base.base_list.SuperViewHolder;
import com.ruitu.arad.util.ScreenUtils;
import com.ruitu.arad.util.SizeUtils;
import com.ruitu.arad.util.ToastUtils;
import com.ruitu.health_2.R;
import com.ruitu.health_2.mvp.model.MallModel;
import com.ruitu.health_2.mvp.presenter.MallPresenter;
import com.ruitu.health_2.ui.adapter.HorizonProListAdapter;
import com.ruitu.health_2.ui.common.util.ViewUtil;
import com.ruitu.router_module.Logg;
import com.ruitu.router_module.bean.home.Advert;
import com.ruitu.router_module.bean.home.HomeData;
import com.ruitu.router_module.bean.home.Model;
import com.ruitu.router_module.bean.product.ProHome;
import com.ruitu.router_module.support.view.FooterHolder;
import com.ruitu.router_module.support.view.MyNestedScrollView;
import com.ruitu.router_module.util.GlideUtil;
import com.youth.banner.Banner;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import me.dkzwm.widget.srl.SmoothRefreshLayout;
import me.dkzwm.widget.srl.config.Constants;
import me.dkzwm.widget.srl.indicator.IIndicator;

public class MallHomeFragment extends BaseFragment<MallPresenter.MallHomeP, MallModel.MallHomeM> {
    private SmoothRefreshLayout refresh;// 外层刷新控件
    private MyNestedScrollView scroll_view;// 滑动控件
    private FrameLayout home_title_bar_layout;// 主页顶部title
    private View home_title_bar_bg_view;// 顶部title背景view

    private LinearLayout ll_scroll;// 所有滚动的内容
    private LinearLayout scan_layout, ll_search;// 标题栏左上角的,搜索
    private RelativeLayout msg_layout;// 右上角消息

    private Banner banner;
    private ImageView iv_banner_holder;// banner的占位图
    private RecyclerView rcv_10_menu, rcv_model;// 10个菜单项,八大模块

    private ImageView iv_new_1, iv_new_2, iv_new_3;// 新人专享左,新人专享右,新人专享3

    private XTabLayout tab, tab_2;// tab tab_2是默认隐藏的tab
    private RelativeLayout rl_tab;// 包含tab_2和下边的分割线的布局
    private RecyclerView rcv_mall_pro;// tab下面的商品 默认不可见的tab下商品 rcv_mall_pro_2
    private RecyclerView rcv_group_buy;// 团购列表
    /************************** 上面是view 下面是数据 **************************/
    private HomeData homeData;// 请求的首页数据

    private List<Advert> advertiseList = new ArrayList<>();// banner广告轮播数据

    private HorizonProListAdapter groupBuyAdapter;// 团购商品的adapter
    private List<ProHome> groupBuyProList = new ArrayList<>();// 团购商品列表

    private MenuAdapter menuAdapter;// 10个菜单项的adapter
    private List<Model> modelList = new ArrayList<>();// 10个菜单项的数据

    private HomeProListAdapter proListAdapter;
    private HomeProListAdapter proListAdapter2;
    private List<ProHome> homeProList = new ArrayList<>();// tab下面的商品列表
    private List<ProHome> homeProList2 = new ArrayList<>();// tab下面的商品列表


    public static final String[] HOME_MODELS = {"精选", "读书会", "文章", "积分", "商品"};// 新五大模块的布局 精选 读书会...
    private int topHeight = 0;// 记录页面上部的高度(banner + menu + 左右俩图 + tab + 上下外边距)
    private int pageHeight = 0;// 记录页面的高度

    private int SCREEN_WIDTH = 0;//屏幕的宽度

    public static MallHomeFragment newInstance() {
        Bundle args = new Bundle();
        MallHomeFragment fragment = new MallHomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SCREEN_WIDTH = ScreenUtils.getScreenWidth();//获取屏幕宽度

        groupBuyAdapter = new HorizonProListAdapter(getActivity());
        proListAdapter = new HomeProListAdapter(getActivity());
        proListAdapter2 = new HomeProListAdapter(getActivity());
    }

    private View header1, header2, header2_2, header3, header4;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_mall_home, container, false);
        home_title_bar_layout = v.findViewById(R.id.home_title_bar_layout);
        home_title_bar_bg_view = v.findViewById(R.id.home_title_bar_bg_view);
        scan_layout = v.findViewById(R.id.scan_layout);
        ll_search = v.findViewById(R.id.ll_search);
        msg_layout = v.findViewById(R.id.msg_layout);
        refresh = v.findViewById(R.id.refresh);
        scroll_view = v.findViewById(R.id.scroll_view);
        tab_2 = v.findViewById(R.id.tab_2);
        ll_scroll = v.findViewById(R.id.ll_scroll);
        rl_tab = v.findViewById(R.id.rl_tab);
//        rcv_mall_pro_2 = v.findViewById(R.id.rcv_mall_pro_2);

        initRefreshView();

        //Banner的布局
        header1 = inflater.inflate(R.layout.home_banner_layout, null, false);
        banner = header1.findViewById(R.id.banner);// Banner布局
        iv_banner_holder = header1.findViewById(R.id.iv_banner_holder);// Banner布局占位图
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) banner.getLayoutParams();
        params.width = SCREEN_WIDTH;
        params.height = params.width * 900 / 1800;// banner的比例是1800 * 900
        banner.setLayoutParams(params);
        iv_banner_holder.setLayoutParams(params);

        //菜单项的布局
        header2 = inflater.inflate(R.layout.home_menu_layout_grid, null, false);
        rcv_10_menu = header2.findViewById(R.id.rcv_10_menu);
        menuAdapter = new MenuAdapter(getActivity());
        GridLayoutManager manager5 = new GridLayoutManager(getActivity(), 5);
        rcv_10_menu.setLayoutManager(manager5);
        rcv_10_menu.setAdapter(menuAdapter);
        for (int i = 0; i < 5; i++) {
            Model model = new Model();
            model.setTitle("加载中");
            modelList.add(model);
        }
        menuAdapter.setDataList(modelList);

        // 团购的布局
        header2_2 = inflater.inflate(R.layout.mall_home_group_buy, null, false);
        rcv_group_buy = header2_2.findViewById(R.id.rcv_group_buy);
        LinearLayoutManager groupBuyManager = new LinearLayoutManager(getActivity());
        groupBuyManager.setOrientation(RecyclerView.HORIZONTAL);
        rcv_group_buy.setLayoutManager(groupBuyManager);
        rcv_group_buy.setAdapter(groupBuyAdapter);
        for (int i = 0; i < 5; i++) {
            ProHome pro = new ProHome();
            pro.setName("团购商品" + i);
            pro.setPrice((97 + i) + "");
            pro.setPic("");
            groupBuyProList.add(pro);
        }
        groupBuyAdapter.setDataList(groupBuyProList);

        // 新人专享模块 左右两张图片
        header4 = inflater.inflate(R.layout.mall_home_newer_special, null, false);
        iv_new_1 = header4.findViewById(R.id.iv_new_1);
        iv_new_2 = header4.findViewById(R.id.iv_new_2);
        iv_new_3 = header4.findViewById(R.id.iv_new_3);

        int[] size = ViewUtil.getHomeNewSpecial3Height(SCREEN_WIDTH);
        LinearLayout.LayoutParams paramIvNew = (LinearLayout.LayoutParams) iv_new_1.getLayoutParams();
        paramIvNew.width = size[0];
        paramIvNew.height = size[1];
        iv_new_1.setLayoutParams(paramIvNew);

        LinearLayout.LayoutParams paramIvNew2 = (LinearLayout.LayoutParams) iv_new_2.getLayoutParams();
        paramIvNew2.width = size[0];
        paramIvNew2.height = size[1];
        iv_new_2.setLayoutParams(paramIvNew2);

        LinearLayout.LayoutParams paramIvNew3 = (LinearLayout.LayoutParams) iv_new_3.getLayoutParams();
        paramIvNew3.width = size[0];
        paramIvNew3.height = size[1];
        iv_new_3.setLayoutParams(paramIvNew3);

        // tab五个模块
        header3 = inflater.inflate(R.layout.mall_home_tab_layout, null, false);
        tab = header3.findViewById(R.id.tab);
        rcv_mall_pro = header3.findViewById(R.id.rcv_mall_pro);
        // 默认设置五个tab
        for (int i = 0; i < 5; i++) {
            tab.addTab(tab.newTab().setText(HOME_MODELS[i]), i);
            tab_2.addTab(tab_2.newTab().setText(HOME_MODELS[i]), i);
        }

        GridLayoutManager mallProManager = new GridLayoutManager(getActivity(), 2);
        rcv_mall_pro.setLayoutManager(mallProManager);
        rcv_mall_pro.setAdapter(proListAdapter);
        // 默认不可见的商品列表
        GridLayoutManager mallProManager2 = new GridLayoutManager(getActivity(), 2);
//        rcv_mall_pro_2.setLayoutManager(mallProManager2);
//        rcv_mall_pro_2.setAdapter(proListAdapter2);
        // tab下面的商品数据
        for (int i = 0; i < 10; i++) {
            ProHome pro = new ProHome();
            pro.setName("商城商品" + i);
            pro.setPrice((98 + i) + "");
            pro.setPic("");
            homeProList.add(pro);
            homeProList2.add(pro);
        }
        proListAdapter.setDataList(homeProList);
        proListAdapter2.setDataList(homeProList2);
//        rcv_mall_pro_2.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
//            @Override
//            public void onLoadMore() {
//                // 加载更多
//                ToastUtils.showShortSafe("加载更多");
//            }
//        });

        scroll_view.post(new TopHeightRunnable());// 计算顶部高度
        scroll_view.post(new PageHeightRunnable());// 计算页面高度

        ll_scroll.addView(header1);// Banner布局
        ll_scroll.addView(header2);// 10个功能菜单布局
        ll_scroll.addView(header2_2);// 团购
        ll_scroll.addView(header4);// 新手专场
        ll_scroll.addView(header3);// tab

        setListeners();

        p.reqHomeData();
        showProgress();

        return v;
    }

    private void reqData() {

    }

    private void initRefreshView() {
        refresh.setEnableAutoLoadMore(true);
        refresh.setDurationToCloseHeader(500);
        refresh.setDurationOfBackToKeepHeader(300);
        refresh.setEnableOverScroll(false);
//        refresh.setLoadingMinTime(1000);// 最少刷新一秒
        refresh.setMode(Constants.MODE_DEFAULT);// MODE_SCALzxE 仿小米下拉拉伸页面的效果

        refresh.setEnableAutoLoadMore(true);
//        refresh.autoLoadMore(true,true);
        refresh.setScrollTargetView(rcv_mall_pro);
    }

    private void setListeners() {
        refresh.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {
                reqData();
                hideProgress();
                showProgress();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refresh.refreshComplete(false, 1000);
                    }
                }, 16000);
            }

            @Override
            public void onLoadingMore() {
                Logg.i("refresh加载更多...");
                ToastUtils.showShortSafe("加载更多...");
                "".charAt(0);
            }
        });
        refresh.addOnStatusChangedListener(new SmoothRefreshLayout.OnStatusChangedListener() {
            @Override
            public void onStatusChanged(byte old, byte now) {
//                Logg.i("onStatusChanged... old = " + old + ",now = " + now);
                if (now == SmoothRefreshLayout.SR_STATUS_INIT) {// 正常状态,显示搜索栏
                    showTitleBar(true);
                } else if (now == SmoothRefreshLayout.SR_STATUS_PREPARE) {// 正在下拉
                    showTitleBar(false);
                } else if (now == SmoothRefreshLayout.SR_STATUS_REFRESHING) {// 正在刷新
                    showTitleBar(false);
                } else if (now == SmoothRefreshLayout.SR_STATUS_COMPLETE) {// 刷新完成(还没有恢复)
                    showTitleBar(false);
                } else if (now == SmoothRefreshLayout.SR_STATUS_LOADING_MORE) {// 看意思是加载更多
                    showTitleBar(true);
                }
            }
        });
        refresh.addOnNestedScrollChangedListener(new SmoothRefreshLayout.OnNestedScrollChangedListener() {
            @Override
            public void onNestedScrollChanged() {
//                Logg.i("onNestedScrollChanged...");
            }
        });
        refresh.addOnUIPositionChangedListener(new SmoothRefreshLayout.OnUIPositionChangedListener() {
            @Override
            public void onChanged(byte status, IIndicator indicator) {
                // 这个回调和addOnStatusChangedListener回调的状态值是一样的
                // 区别:OnStatusChanged状态相同时不执行,只有状态改变时执行 onChanged:一直回调当前状态
            }
        });

        scroll_view.setScrollViewListener(new MyNestedScrollView.ScrollViewListener() {
            @Override
            public void onScrollChanged(MyNestedScrollView scrollView, int x, int y, int oldx, int oldy) {
//                Logg.i("y = " + y + ",topHeight = " + topHeight + ",pageHeight = " + pageHeight);
                if (y > topHeight) {// 滑动超过了顶部(banner + menu + 左右俩图)
                    rl_tab.setVisibility(View.VISIBLE);
//                    rcv_mall_pro.setVisibility(View.GONE);
                } else {
//                    rcv_mall_pro.setVisibility(View.VISIBLE);
                    rl_tab.setVisibility(View.GONE);
                }
            }
        });

        setOnClickListener(scan_layout);
    }

    @Override
    public void onClick(View view) {
        if (view == scan_layout) {
            getActivity().finish();
        }
    }

    private void showTitleBar(boolean isShow) {
        if (isShow) {
            if (home_title_bar_layout.getVisibility() == View.GONE) {
                home_title_bar_layout.setVisibility(View.VISIBLE);
            }
        } else {
            if (home_title_bar_layout.getVisibility() == View.VISIBLE) {
                home_title_bar_layout.setVisibility(View.GONE);
            }
        }
    }

    //banner下面的菜单项的adapter
    private static class MenuAdapter extends ListBaseAdapter<Model> {

        private int[] menuIcon = {R.drawable.home_ic_menu_4_dfts, R.drawable.home_ic_menu_0_tyt
                , R.drawable.home_ic_menu_1_gyg, R.drawable.home_ic_menu_2_chj, R.drawable.home_ic_menu_3_cjqc
                , R.drawable.home_ic_menu_5_hyjp, R.drawable.home_ic_menu_6_tjsp, R.drawable.home_ic_menu_7_jjsj
                , R.drawable.home_ic_menu_8_yhq, R.drawable.home_ic_menu_9_grzx};

        public MenuAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.home_item_menu;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int pos) {
            TextView tv_menu_txt = holder.getView(R.id.tv_menu_txt);
            ImageView iv_menu_icon = holder.getView(R.id.iv_menu_icon);

            Model model = mDataList.get(pos);
            tv_menu_txt.setText(model.getTitle());
            iv_menu_icon.setImageResource(menuIcon[pos]);
        }
    }

    private class HomeProListAdapter extends ListBaseAdapter<ProHome> {

        public HomeProListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_mall_home_tab_pro;
        }

        @Override
        public int getItemCount() {
//            return super.getItemCount() + 1;// 最后一个"加载更多的时候用到"
            return super.getItemCount();
        }

        @Override
        public int getItemViewType(int position) {
            if (position == mDataList.size()) {//最后一个 是底部item
                return 1;
            } else {
                return 0;
            }
        }

        @Override
        public SuperViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == 1) {
                View view = View.inflate(getActivity(), R.layout.footer_layout, null);
                FooterHolder footerHolder = new FooterHolder(view);
                return footerHolder;
            } else {
                return super.onCreateViewHolder(parent, viewType);
            }
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, int position) {
            if (holder instanceof FooterHolder) {
                TextView tv = holder.getView(R.id.tv_txt);
//                if () {
//                    tv.setText("加载完成");
//                } else {
//                    tv.setText("加载中...");
//                }
            } else {
                ImageView icon = holder.getView(R.id.icon);// 图片
                TextView tv_name = holder.getView(R.id.tv_name);// 名称
                TextView tv_price = holder.getView(R.id.tv_price);// 价格
                TextView tv_integral = holder.getView(R.id.tv_integral);// 积分

                int width = ScreenUtils.getScreenWidth();
                int itemWidth = (width - SizeUtils.dp2px(30)) / 2;

                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) icon.getLayoutParams();
                params.width = itemWidth;
                params.height = itemWidth;
                icon.setLayoutParams(params);

                ProHome pro = mDataList.get(position);
                tv_name.setText(pro.getName());
                tv_price.setText("￥" + pro.getPrice());
                GlideUtil.loadImg(pro.getPic(), icon);

                try {
                    if (Integer.parseInt(pro.getGiftPoint()) > 0) {
                        tv_integral.setText("送" + pro.getGiftPoint() + "积分");
                    } else {
                        tv_integral.setText("");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    tv_integral.setText("");
                }
            }
        }
    }

    // 计算首页顶部高度
    private class TopHeightRunnable implements Runnable {
        @Override
        public void run() {
            int bannerHei = banner.getMeasuredHeight();
            int menuHei = rcv_10_menu.getMeasuredHeight();
            int imgHei = iv_new_1.getMeasuredHeight();
            int groupBuyHei = header2_2.getMeasuredHeight();
            int margin = SizeUtils.dp2px(40);
            topHeight = bannerHei + menuHei + imgHei + groupBuyHei + margin;
        }
    }

    // 计算首页高度
    private class PageHeightRunnable implements Runnable {
        @Override
        public void run() {
            pageHeight = scroll_view.getMeasuredHeight();
        }
    }
}
